package com.jiuzhi.client.main;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.jiuzhi.client.handler.MinaShortClientHandler;

public class MinaShortClient {
	 private static final int PORT = 8002;
		private static  NioSocketConnector connector;
	  IoSession session;

	    public static void main(String[] args) throws IOException,InterruptedException {

	         connector = new NioSocketConnector();

	       connector.getSessionConfig().setReadBufferSize(2048);
	       connector.getFilterChain().addLast("logger", new LoggingFilter());
	       connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
	       connector.setHandler(new MinaShortClientHandler());

	     //  for (int i = 1; i <= 3; i++) {

	           ConnectFuture future = connector.connect(new InetSocketAddress("172.16.1.54",PORT));

	           future.awaitUninterruptibly();

	           IoSession session =future.getSession();

	    }
	    
		/**
		 * 断开链接
		 */
		public void disConnect(){
			if(this.session!=null&&this.session.getCloseFuture()!=null&&connector!=null){
				//等待链接断开
				this.session.getCloseFuture().awaitUninterruptibly();
				connector.dispose();
				 System.exit(0);
			}
		}

}
